package com.databaseconnectionmobilapi.interceptor;

import com.databaseconnectionmobilapi.annotation.LoginInterceptor;
import com.databaseconnectionmobilapi.service.RedisService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author Fall
 */
@Slf4j
public class AuthorityInterceptor extends HandlerInterceptorAdapter {
    @Resource
    private RedisService redisService;

    public AuthorityInterceptor() {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        Method method = handlerMethod.getMethod();

        LoginInterceptor loginInterceptor = method.getAnnotation(LoginInterceptor.class);

        if (loginInterceptor != null) {
            log.info("执行登录操作");

            return true;
        }

        String token = request.getHeader("token");
        if (redisService.get(token, String.class) == null) {
            response.setStatus(405);
            return false;
        }

        return true;
    }
}
